from pathlib import Path

from tools import WordReplace
from pandas import read_excel
from ...base import ThreadBase
from traceback import format_exc


class WordReplaceThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.template_path = None
        self.excel_path = None
        self.save_path = None
        self._dict = None

    def run(self):
        excel_pd = read_excel(self.excel_path)
        try:
            for i in range(len(excel_pd)):
                word = WordReplace(self.template_path)
                _dict = word.get_dict()

                orient = excel_pd.loc[i]
                for k, v in self._dict.items():
                    _dict[k] = orient[v]
                word.set_dict(_dict)
                file = str(Path(self.save_path) / orient[self._dict['保存文件名称']]) + '.docx'
                word.replace_save(file)
        except Exception as e:
            print(format_exc())
            self.error.emit(format_exc())

    def set_value(
            self,
            template_path: str,
            excel_path: str,
            save_path: str,
            _dict: dict
    ):
        self.template_path = template_path
        self.excel_path = excel_path
        self.save_path = save_path
        self._dict = _dict
